package com.yoomiito.app.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.yoomiito.app.Constant;
import com.yoomiito.app.R;
import com.yoomiito.app.adapter.CouponGoodsAdapter;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseActivity;
import com.yoomiito.app.model.HaoDanKuInfo;
import com.yoomiito.app.model.home.HaoDanKuData;
import com.yoomiito.app.present.CouponGoodsPresenter;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.Const;
import com.yoomiito.app.utils.DensityUtil;
import com.yoomiito.app.utils.RouterUtils;
import com.yoomiito.app.widget.TabView;
import com.yoomiito.app.widget.state.ContentType;
import com.yoomiito.app.widget.state.EmptyType;
import com.yoomiito.app.widget.state.StatusManager;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 淘宝商品  9.9  大额优惠券 等
 * sort 0.综合（最新），1.券后价(低到高)，2.券后价（高到低），3.券面额（高到低），4.月销量（高到低），
 * 5.佣金比例（高到低），6.券面额（低到高），7.月销量（低到高），8.佣金比例（低到高），9.全天销量（高到低），
 * 10全天销量（低到高），11.近2小时销量（高到低），12.近2小时销量（低到高），13.优惠券领取量（高到低），14.好单库指数（高到低）
 * coupon_min 1代表有优惠券 0 无
 */
public class CouponGoodsActivity extends BaseActivity<CouponGoodsPresenter> {

    @BindView(R.id.tv_center)
    TextView mTitleTv;
    @BindView(R.id.act_coupon_goods_tabView)
    TabView mTabView;
    @BindView(R.id.act_coupon_goods_fl)
    FrameLayout mFrameLayout;
//    @BindView(R.url.act_coupon_goods_rcy)
    RecyclerView mRecyclerView;
    SmartRefreshLayout mSmartRefreshLayout;
    private List<DelegateAdapter.Adapter> adapters = new LinkedList<>();
    private CouponGoodsAdapter goodsAdapter;
    private List<HaoDanKuInfo> mHaoDanKuInfos = new ArrayList<>();
    private String url;
    private int mSort = 0;
    private int mHasCoupon = 0;
    private long currentPage = 1;
    private String mSourceType = "";//从广告页过来 advert_banner  其他页面过来得为空
    @Override
    public int getLayoutId() {
        return R.layout.act_coupon_goods;
    }

    @Override
    public CouponGoodsPresenter newP() {
        return new CouponGoodsPresenter(App.mAppConfig);
    }

    public static void start(Context context,String url,String data){
        Intent intent = new Intent(context,CouponGoodsActivity.class);
        intent.putExtra(Constant.ID,url);
        intent.putExtra(Constant.DATA, data);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static void start(Context context,String url,String data,String type){
        Intent intent = new Intent(context,CouponGoodsActivity.class);
        intent.putExtra(Constant.ID,url);
        intent.putExtra(Constant.DATA, data);
        if (!TextUtils.isEmpty(type)){
            intent.putExtra(Const.Common.Type,type);
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mStatusManager = new StatusManager.Builder(this)
                .addType(new ContentType(R.layout.fm_rcy))
                .addType(new EmptyType())
                .build();
        mRecyclerView = mStatusManager.view().findViewById(R.id.fm_rcy);
        SmartRefreshLayout.LayoutParams lp = (SmartRefreshLayout.LayoutParams) mRecyclerView.getLayoutParams();
        lp.topMargin = DensityUtil.dp2px(11);
        mSmartRefreshLayout = mStatusManager.view().findViewById(R.id.fm_refreshLayout);
        mFrameLayout.addView(mStatusManager.view());
        Intent intent = getIntent();
        url = intent.getStringExtra(Constant.ID);
        mTitleTv.setVisibility(View.VISIBLE);
        mTitleTv.setText(intent.getStringExtra(Constant.DATA));
        mSourceType = intent.getStringExtra(Const.Common.Type);
        initTab();
        initRcy();
        initRefresh();
    }

    private void initRefresh() {
        mSmartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            currentPage = 1;
            getP().getHaoDanku(url, mSort, mHasCoupon,currentPage,mSourceType);
        });
        mSmartRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
            getP().getHaoDanku(url, mSort, mHasCoupon,currentPage,mSourceType);
        });
        mSmartRefreshLayout.autoRefresh();
    }

    private void initRcy() {
        VirtualLayoutManager layoutManager = new VirtualLayoutManager(context);
        mRecyclerView.setLayoutManager(layoutManager);

        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        viewPool.setMaxRecycledViews(0, 10);
        mRecyclerView.setRecycledViewPool(viewPool);

        GridLayoutHelper gridLayoutHelper = new GridLayoutHelper(2);
        gridLayoutHelper.setHGap(DensityUtil.dp2px(5));
        gridLayoutHelper.setVGap(DensityUtil.dp2px(5));
        gridLayoutHelper.setMargin(DensityUtil.dp2px(12), 0,DensityUtil.dp2px(12), 0);
        gridLayoutHelper.setAutoExpand(false);
        goodsAdapter = new CouponGoodsAdapter(this, mHaoDanKuInfos, gridLayoutHelper);
        goodsAdapter.setItemClickListener(position -> {
            HaoDanKuInfo info = mHaoDanKuInfos.get(position);
            RouterUtils.toGoodsDetail(CouponGoodsActivity.this, String.valueOf(info.getItemid()), AllCode.TaoBao);
        });
        adapters.add(goodsAdapter);

        DelegateAdapter delegateAdapter = new DelegateAdapter(layoutManager);
        delegateAdapter.setAdapters(adapters);
        mRecyclerView.setAdapter(delegateAdapter);

    }

    private void initTab() {
        mTabView.setDefault()
                .dismissCoupon();
//        mTabView.setOnChangeListener((sort, hasCoupon) -> {
//            mHasCoupon = hasCoupon;
//            switch (sort) {
//                case "price_asc":
//                    mSort = 1;
//                    break;
//                case "price_des":
//                    mSort = 2;
//                    break;
//                case "total_sales_des":
//                    mSort = 4;
//                    break;
//                case "total_sales_asc":
//                    mSort = 7;
//                    break;
//                case "":
//                    mSort = 0;
//                    break;
//            }
//            currentPage = 1;
//            showLoading();
//            getP().getHaoDanku(url, mSort, mHasCoupon,currentPage,mSourceType);
//        });
    }

    public void setData(HaoDanKuData haoDanKuData) {
        List<HaoDanKuInfo> data = haoDanKuData.getData();
        if (currentPage==1){
            mHaoDanKuInfos.clear();
            mSmartRefreshLayout.finishRefresh(true);
            if (data==null||data.size()==0){
                mStatusManager.showEmpty();
            }else {
                mHaoDanKuInfos.addAll(data);
                goodsAdapter.notifyDataSetChanged();
                mStatusManager.showContent();
            }
        }else {
            mSmartRefreshLayout.finishLoadMore(true);
            if (data==null||data.size()==0){
                mSmartRefreshLayout.finishLoadMoreWithNoMoreData();
            }else {
                mHaoDanKuInfos.addAll(data);
                goodsAdapter.notifyDataSetChanged();
            }
        }
        currentPage = haoDanKuData.getMin_id();//分页使用
    }

    @OnClick({R.id.iv_back_left})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back_left:
                finish();
                break;
        }
    }


}
